import { createStore ,Commit} from 'vuex'
import axios, { AxiosRequestConfig } from 'axios'
const asyncAndCommit = async (url: string, mutationName: string,
  commit: Commit,
  config: AxiosRequestConfig = { method: 'get' },
  extraData?: any) => {
  const { data } = await axios(url, config)
  if (extraData) {
    commit(mutationName, { data, extraData })
  } else {
    commit(mutationName, data)
  }
  return data
}
export interface GlobalDataProps {
  token: string;
  error: object;
  loading: boolean;
  columns: GlobalColumnsProps;
  banner:object
}
export interface GlobalColumnsProps {
  count?:number
  limit?:string
  name?:string
  skip:string
  wallpapers:Array<ColumnProps>
}
export interface ColumnProps {
  author?:Object
  classifys?:any
  collectCount:number
  createTime?:string
  downloadCount?:number
  hasCollect?:number
  lastModifiedTime?:string
  settingUpCount?:number
  tags?:any
  wallpaperDesc?:string
  wallpaperId?:string
  wallpaperImg?:any
  wallpaperName?:string
  love?:boolean
  }
export default createStore<GlobalDataProps>({
  state: {
      token: localStorage.getItem('token') || '',
      columns: { wallpapers: [], skip: '0' },
      banner: {},
      error: { status: false },
      loading: false,
  },
  mutations: {
    login(state, rawData) {
      const token = rawData.data
      state.token = token
      localStorage.setItem('token', token)
    },
    banner(state, rawData) {
      state.banner = rawData.data
    },
    columns(state, rawData) {
      state.columns = rawData.data
    },
    delete(state,index){
      state.columns.wallpapers.splice(index,1)
    },
    love(state){
      for(let i=0;state.columns.wallpapers.length;i++){
        state.columns.wallpapers[i].hasCollect=1
      }
    },
    addColumns(state, data){
      state.columns.skip=data.skip
      console.log(state.columns)
      state.columns.wallpapers=state.columns.wallpapers.concat(data.wallpapers)
    },
    setLoading(state, status) {
      state.loading = status
    },
    setError(state, e) {
      state.error = e
    },
    setLove(state,index){
      console.log( state.columns.wallpapers[index])
      state.columns.wallpapers[index].hasCollect=1
      state.columns.wallpapers[index].collectCount+=1
    }
  },
  actions: {
    banner({ commit }) {
      commit('setLoading', true)
      return asyncAndCommit('/apis/wallpapercontent/wallpaper/banner/top_banner_content', 'banner', commit, { method: 'get'})
    },
    getList({ commit},url) {
      commit('setLoading', true)
      return asyncAndCommit(`/apis/${url}`, 'columns', commit, { method: 'get'})
    },
    loginAndFetch({ commit,state }, payload) {
      console.log(typeof state.token)
      if(state.token.length>0&&state.token!="undefined"){
        return
      }
      return asyncAndCommit('/apis/appbase/token/register', 'login', commit, { method: 'post', data: payload })
    }
  },
  modules: {
  }
})
